const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const { generateOrderNumber } = require('../utils/orderNumber');


// 获取所有订单
exports.getAllOrders = async (req, res) => {
  try {
    const { page = 1, limit = 20, status, startDate, endDate, search, channelId } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建过滤条件
    const where = {};
    if (status) where.status = status;
    if (channelId) where.channelId = Number(channelId);
    
    // 声明变量以便在整个函数范围内使用
    let start, end;
    
    if (startDate && endDate) {
      // 修改日期处理逻辑，考虑时区差异
      // 解析日期字符串为本地日期对象
      const startDateParts = startDate.split('-').map(Number);
      const endDateParts = endDate.split('-').map(Number);
      
      // 创建日期对象，月份需要减1（JavaScript中月份从0开始）
      start = new Date(startDateParts[0], startDateParts[1] - 1, startDateParts[2], 0, 0, 0, 0);
      end = new Date(endDateParts[0], endDateParts[1] - 1, endDateParts[2], 23, 59, 59, 999);
      
      console.log(`查询日期范围(本地时间): ${start.toString()} 到 ${end.toString()}`);
      console.log(`查询日期范围(ISO): ${start.toISOString()} 到 ${end.toISOString()}`);
      
      // 确保使用>=当天开始和<=当天结束的比较
      where.createdAt = {
        gte: start,
        lte: end
      };
    }
    if (search) {
      where.OR = [
        { orderNo: { contains: search } },
        { items: { some: { product: { name: { contains: search } } } } }
      ];
    }
    
    // 查询订单
    const orders = await prisma.order.findMany({
      skip,
      take: Number(limit),
      where,
      include: {
        user: { select: { id: true, username: true, name: true } },
        channel: true,
        payments: {
          take: 1,
          orderBy: { createdAt: 'desc' },
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        }
      },
      orderBy: { createdAt: 'desc' }
    });
    
    // 获取总数
    const total = await prisma.order.count({ where });
    
    // 构建响应对象
    const responseData = {
      status: 'success',
      data: orders,
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        pages: Math.ceil(total / limit)
      }
    };
    
    // 只有当start和end变量已定义时，才添加dateRange
    if (start && end) {
      responseData.meta.dateRange = {
        start: start.toISOString(),
        end: end.toISOString(),
        startDate, // 添加原始日期字符串，便于调试
        endDate
      };
    }
    
    res.json(responseData);
  } catch (error) {
    console.error('获取订单失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取订单失败',
      error: error.message
    });
  }
};

// 获取单个订单
exports.getOrderById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const order = await prisma.order.findUnique({
      where: { id: Number(id) },
      include: {
        user: { select: { id: true, username: true, name: true } },
        channel: true,
        items: {
          include: {
            product: true
          }
        },
        payments: {
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        }
      }
    });
    
    if (!order) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }
    
    res.json({
      status: 'success',
      data: order
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取订单详情失败',
      error: error.message
    });
  }
};

// 创建订单
exports.createOrder = async (req, res) => {
  try {
    console.log('创建订单 - 请求体:', req.body);
    console.log('当前用户:', req.user);
    
    const { items, total, channelId, paymentMethod, note } = req.body;
    
    // 验证数据
    if (!items || !Array.isArray(items) || items.length === 0) {
      console.log('订单验证失败: 缺少商品项目');
      return res.status(400).json({
        status: 'error',
        message: '订单必须包含商品项目'
      });
    }

    // 验证商品项
    for (const item of items) {
      if (!item.productId || !item.quantity || !item.price) {
        console.log('订单验证失败: 商品项数据不完整', item);
        return res.status(400).json({
          status: 'error',
          message: '商品项数据不完整'
        });
      }
    }
    
    // 验证支付方式
    const validPaymentMethods = ['cash', 'wechat', 'alipay', 'mixed', 'complimentary'];
    if (paymentMethod && !validPaymentMethods.includes(paymentMethod)) {
      console.log('订单验证失败: 无效的支付方式', paymentMethod);
      return res.status(400).json({
        status: 'error',
        message: '无效的支付方式'
      });
    }
    
    // 生成订单号
    const orderNo = generateOrderNumber();
    console.log('生成订单号:', orderNo);
    
    // 临时修复：如果req.user不存在，使用默认用户ID
    const userId = req.user ? req.user.id : 1;
    console.log('使用用户ID:', userId);
    
    try {
      // 使用事务确保数据一致性
      const result = await prisma.$transaction(async (prisma) => {
        console.log('开始事务处理');
        
        // 创建订单
        console.log('创建订单记录, 用户ID:', userId);
        const order = await prisma.order.create({
          data: {
            orderNo,
            userId: userId,
            channelId: channelId || null,
            total,
            status: 'pending',
            note: note || null
          }
        });
        console.log('订单创建成功:', order);
        
        // 创建订单项目和减少库存
        console.log('开始创建订单项目和减少库存');
        for (const item of items) {
          console.log('创建订单项:', item);
          await prisma.orderItem.create({
            data: {
              orderId: order.id,
              productId: item.productId,
              quantity: item.quantity,
              price: item.price
            }
          });
          
          // 查询商品信息
          const product = await prisma.product.findUnique({
            where: { id: item.productId }
          });
          
          if (product) {
            // 计算减少后的库存数量
            const currentStock = parseFloat(product.stockQuantity) || 0;
            const orderQuantity = parseFloat(item.quantity) || 0;
            const newStock = Math.max(0, currentStock - orderQuantity);
            
            // 更新商品库存
            await prisma.product.update({
              where: { id: item.productId },
              data: { 
                stockQuantity: newStock,
                // 根据库存量更新库存状态
                stockStatus: getStockStatus(newStock, product.minimumStock, product.maximumStock)
              }
            });
            
            // 记录库存变动
            await prisma.stockMovement.create({
              data: {
                productId: item.productId,
                // 默认使用第一个仓库，实际应用中应该指定
                warehouseId: 1,
                movementType: 2, // 2表示出库
                quantity: orderQuantity,
                beforeQuantity: currentStock,
                afterQuantity: newStock,
                operatorId: userId,
                remarks: `订单出库: ${orderNo}`
              }
            });
          }
        }
        console.log('订单项目创建和库存更新完成');
        
        // 创建支付记录
        if (paymentMethod) {
          console.log('创建支付记录, 方式:', paymentMethod);
          
          // 如果是招待，则金额为0，否则为订单总额
          const paymentAmount = paymentMethod === 'complimentary' ? 0 : total;
          
          await prisma.payment.create({
            data: {
              orderId: order.id,
              method: paymentMethod,
              amount: paymentAmount,
              status: 'completed'
            }
          });
          
          // 更新订单状态为已支付
          console.log('更新订单状态为已支付');
          await prisma.order.update({
            where: { id: order.id },
            data: { status: 'paid' }
          });
        }
        
        // 返回完整订单
        console.log('查询完整订单信息');
        return prisma.order.findUnique({
          where: { id: order.id },
          include: {
            user: { select: { id: true, username: true, name: true } },
            channel: true,
            items: {
              include: {
                product: true
              }
            },
            payments: {
              select: {
                id: true,
                orderId: true,
                method: true,
                amount: true,
                status: true,
                createdAt: true,
                updatedAt: true
              }
            }
          }
        });
      });
      
      console.log('订单处理完成, 返回结果:', result);
      
      // 记录审计日志
      await logAudit({
        userId: userId,
        action: 'create',
        module: 'order',
        description: `创建订单 ${result.orderNo}`,
        details: JSON.stringify(result)
      });
      
      res.status(201).json({
        status: 'success',
        message: '订单创建成功',
        data: result
      });
    } catch (transactionError) {
      console.error('事务执行失败:', transactionError);
      throw transactionError;
    }
  } catch (error) {
    console.error('创建订单失败:', error);
    res.status(500).json({
      status: 'error',
      message: '创建订单失败',
      error: error.message,
      stack: error.stack
    });
  }
};

// 更新订单状态
exports.updateOrderStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    const orderId = Number(id);
    
    // 验证状态值
    const validStatuses = ['pending', 'paid', 'completed', 'cancelled', 'refunded'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        status: 'error',
        message: '无效的订单状态'
      });
    }
    
    // 查询当前订单信息
    const existingOrder = await prisma.order.findUnique({
      where: { id: orderId },
      include: {
        items: {
          include: {
            product: true
          }
        }
      }
    });
    
    if (!existingOrder) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }
    
    // 获取当前用户ID
    const userId = req.user ? req.user.id : 1;
    
    // 使用事务进行处理
    const updatedOrder = await prisma.$transaction(async (prisma) => {
      // 更新订单状态
      const order = await prisma.order.update({
        where: { id: orderId },
        data: { status }
      });
      
      // 当订单状态更新为取消或退款时，恢复库存
      if ((status === 'cancelled' || status === 'refunded') && 
          (existingOrder.status === 'paid' || existingOrder.status === 'completed')) {
        
        console.log(`订单${existingOrder.orderNo}状态更新为${status}，需要恢复库存`);
        
        // 遍历订单项目，恢复库存
        for (const item of existingOrder.items) {
          const product = await prisma.product.findUnique({
            where: { id: item.productId }
          });
          
          if (product) {
            // 计算恢复后的库存数量
            const currentStock = parseFloat(product.stockQuantity) || 0;
            const orderQuantity = parseFloat(item.quantity) || 0;
            const newStock = currentStock + orderQuantity;
            
            console.log(`恢复商品${product.name}库存: ${currentStock} + ${orderQuantity} = ${newStock}`);
            
            // 更新商品库存
            await prisma.product.update({
              where: { id: item.productId },
              data: { 
                stockQuantity: newStock,
                // 根据库存量更新库存状态
                stockStatus: getStockStatus(newStock, product.minimumStock, product.maximumStock)
              }
            });
            
            // 记录库存变动
            await prisma.stockMovement.create({
              data: {
                productId: item.productId,
                warehouseId: 1, // 默认使用第一个仓库
                movementType: 1, // 1表示入库
                quantity: orderQuantity,
                beforeQuantity: currentStock,
                afterQuantity: newStock,
                operatorId: userId,
                remarks: `订单退货入库: ${existingOrder.orderNo}`
              }
            });
          }
        }
      }
      
      return order;
    });
    
    // 记录审计日志
    await logAudit({
      userId: userId,
      action: 'update',
      module: 'order',
      description: `更新订单状态: ${existingOrder.orderNo} 从 ${existingOrder.status} 到 ${status}`,
      details: JSON.stringify(updatedOrder)
    });
    
    res.json({
      status: 'success',
      message: '订单状态更新成功',
      data: updatedOrder
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      status: 'error',
      message: '更新订单状态失败',
      error: error.message
    });
  }
};

// 添加支付记录
exports.addPayment = async (req, res) => {
  try {
    const { id } = req.params;
    const { method, amount } = req.body;
    
    // 验证数据
    if (!method) {
      return res.status(400).json({
        status: 'error',
        message: '支付方式为必填项'
      });
    }
    
    // 验证支付方式
    const validPaymentMethods = ['cash', 'wechat', 'alipay', 'mixed', 'complimentary'];
    if (!validPaymentMethods.includes(method)) {
      return res.status(400).json({
        status: 'error',
        message: '无效的支付方式'
      });
    }
    
    // 如果是招待，金额为0
    const paymentAmount = method === 'complimentary' ? 0 : (amount || 0);
    
    // 创建支付记录
    const payment = await prisma.payment.create({
      data: {
        orderId: Number(id),
        method,
        amount: paymentAmount,
        status: 'completed'
      }
    });
    
    // 更新订单状态
    await prisma.order.update({
      where: { id: Number(id) },
      data: { status: 'paid' }
    });
    
    res.status(201).json({
      status: 'success',
      message: '支付记录添加成功',
      data: payment
    });
  } catch (error) {
    console.error('添加支付记录失败:', error);
    res.status(500).json({
      status: 'error',
      message: '添加支付记录失败',
      error: error.message
    });
  }
};

// 更新订单
exports.updateOrder = async (req, res) => {
  try {
    const { id } = req.params;
    const { note, channelId } = req.body;
    
    // 查找订单是否存在
    const order = await prisma.order.findUnique({
      where: { id: Number(id) }
    });
    
    if (!order) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }
    
    // 只允许修改特定字段
    const updateData = {};
    
    if (note !== undefined) {
      updateData.note = note;
    }
    
    if (channelId !== undefined) {
      updateData.channelId = channelId || null;
    }
    
    // 更新订单
    const updatedOrder = await prisma.order.update({
      where: { id: Number(id) },
      data: updateData,
      include: {
        user: { select: { id: true, username: true, name: true } },
        channel: true,
        items: {
          include: {
            product: true
          }
        },
        payments: true
      }
    });
    
    res.json({
      status: 'success',
      message: '订单更新成功',
      data: updatedOrder
    });
  } catch (error) {
    console.error('更新订单失败:', error);
    res.status(500).json({
      status: 'error',
      message: '更新订单失败',
      error: error.message
    });
  }
};

// 删除订单
exports.deleteOrder = async (req, res) => {
  try {
    const { id } = req.params;
    const orderId = Number(id);
    
    // 验证订单是否存在
    const order = await prisma.order.findUnique({
      where: { id: orderId },
      include: {
        items: true,
        payments: true
      }
    });
    
    if (!order) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }
    
    // 使用事务确保数据一致性
    await prisma.$transaction(async (prisma) => {
      // 先删除关联的订单项
      if (order.items.length > 0) {
        await prisma.orderItem.deleteMany({
          where: { orderId }
        });
      }
      
      // 再删除关联的支付记录
      if (order.payments.length > 0) {
        await prisma.payment.deleteMany({
          where: { orderId }
        });
      }
      
      // 最后删除订单
      await prisma.order.delete({
        where: { id: orderId }
      });
    });
    
    res.json({
      status: 'success',
      message: '订单删除成功'
    });
  } catch (error) {
    console.error('删除订单失败:', error);
    res.status(500).json({
      status: 'error',
      message: '删除订单失败',
      error: error.message
    });
  }
};

// 通过订单号更新订单状态
exports.updateOrderStatusByOrderNo = async (req, res) => {
  try {
    const { orderNo } = req.params;
    const { status } = req.body;
    
    // 验证状态值
    const validStatuses = ['pending', 'paid', 'completed', 'cancelled', 'refunded'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        status: 'error',
        message: '无效的订单状态'
      });
    }
    
    // 根据订单号查询订单
    const existingOrder = await prisma.order.findFirst({
      where: { orderNo },
      include: {
        items: {
          include: {
            product: true
          }
        }
      }
    });
    
    if (!existingOrder) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }
    
    // 获取当前用户ID
    const userId = req.user ? req.user.id : 1;
    
    // 使用事务进行处理
    const updatedOrder = await prisma.$transaction(async (prisma) => {
      // 更新订单状态
      const order = await prisma.order.update({
        where: { id: existingOrder.id },
        data: { status }
      });
      
      // 当订单状态更新为取消或退款时，恢复库存
      if ((status === 'cancelled' || status === 'refunded') && 
          (existingOrder.status === 'paid' || existingOrder.status === 'completed')) {
        
        console.log(`订单${existingOrder.orderNo}状态更新为${status}，需要恢复库存`);
        
        // 遍历订单项目，恢复库存
        for (const item of existingOrder.items) {
          const product = await prisma.product.findUnique({
            where: { id: item.productId }
          });
          
          if (product) {
            // 计算恢复后的库存数量
            const currentStock = parseFloat(product.stockQuantity) || 0;
            const orderQuantity = parseFloat(item.quantity) || 0;
            const newStock = currentStock + orderQuantity;
            
            console.log(`恢复商品${product.name}库存: ${currentStock} + ${orderQuantity} = ${newStock}`);
            
            // 更新商品库存
            await prisma.product.update({
              where: { id: item.productId },
              data: { 
                stockQuantity: newStock,
                // 根据库存量更新库存状态
                stockStatus: getStockStatus(newStock, product.minimumStock, product.maximumStock)
              }
            });
            
            // 记录库存变动
            await prisma.stockMovement.create({
              data: {
                productId: item.productId,
                warehouseId: 1, // 默认使用第一个仓库
                movementType: 1, // 1表示入库
                quantity: orderQuantity,
                beforeQuantity: currentStock,
                afterQuantity: newStock,
                operatorId: userId,
                remarks: `订单退货入库: ${existingOrder.orderNo}`
              }
            });
          }
        }
      }
      
      return order;
    });
    
    // 记录审计日志
    await logAudit({
      userId: userId,
      action: 'update',
      module: 'order',
      description: `更新订单状态: ${existingOrder.orderNo} 从 ${existingOrder.status} 到 ${status}`,
      details: JSON.stringify(updatedOrder)
    });
    
    res.json({
      status: 'success',
      message: '订单状态更新成功',
      data: updatedOrder
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      status: 'error',
      message: '更新订单状态失败',
      error: error.message
    });
  }
};

// 辅助函数：根据库存数量、最低库存和最高库存计算库存状态
function getStockStatus(stockQuantity, minimumStock, maximumStock) {
  if (stockQuantity <= 0) {
    return 'out_of_stock'; // 缺货
  } else if (minimumStock && stockQuantity <= minimumStock) {
    return 'warning'; // 预警
  } else if (maximumStock && stockQuantity > maximumStock) {
    return 'excess'; // 超储
  } else {
    return 'normal'; // 正常
  }
} 